package parser

import (
	"os"
	"save-kindle/entity"
	"save-kindle/log"
	"save-kindle/source"
	"strings"
)

type EpubParserV2 struct {
	DefaultEpubParser
	Article chan entity.Article
	Book    source.Book
}

// NewEpubParser 构建解析器
func NewEpubParserV2(book source.Book) EpubParserV2 {
	bookInfo := book.GetBookInfo()

	// 构建
	return EpubParserV2{
		DefaultEpubParser: NewDefaultEpubParser(bookInfo.BookName),
		Article:           make(chan entity.Article, 20),
		Book:              book,
	}
}

// Parser 把网页源数据解析下来
func (parser EpubParserV2) Parser() {
	// originFilePath 原始内容文件地址
	originPath := parser.Path + "origin/"
	err := os.MkdirAll(originPath, 0777)
	if err != nil {
		log.PrintErr(err)
	}

	// 获取目录
	catalog, err := parser.Book.GetCatalog()
	if err != nil {
		log.PrintErr(err)
	}

	// 开始写入文件
	for i := range catalog {
		go func(index int, path string) {
			log.Println(index, catalog[index])
			article := catalog[index]
			article, _ = parser.Book.GetArticleContent(article)
			//util.WriteFile(index, path, article)
			parser.Article <- article
		}(i, originPath)
	}

	parser.gen(len(catalog))
}

// ------------------------- 生成 -----------------------

func (parser EpubParserV2) gen(size int) {
	parser.DefaultEpubParser.Gen()

	list := make([]TableContentItem, 0)
	itemMap := make(map[int]TableContentItem, size)
	countList := make([]int, 0)

	finish := 0
	for size != finish {
		select {
		case article := <-parser.Article:
			parser.genXhtml(EpubChapter{
				FileName: parser.BookName,
				CurCount: article.Index,
				Title:    article.ArticleName,
				Content:  strings.Split(article.ArticleContent, "\n"),
			})

			itemMap[article.Index] = TableContentItem{
				CurCount: article.Index,
				Title:    article.ArticleName,
			}
			countList = append(countList, article.Index)
			log.Println("finish:", article.ArticleName)
			finish++
		}
	}

	log.Println(finish)

	for i := 0; i < size; i++ {
		list = append(list, itemMap[i])
	}

	parser.genTableContents(TableContent{
		Item: list,
	})

	parser.genOpf(countList)
	parser.genZipFile()
}
